//
//  MapViewController.m
//  Memo Pad
//
//  Created by MacBook Pro on 10/19/12.
//
//

#import "MapViewController.h"
#import "cLanguage.h"
#define Default_Zoom_Level 16
//#define Zoom_Min_Level 13

@interface MapViewController ()

-(void)Cancel;
-(void)LoadData;
-(void)CreateCompanyData;

-(UIImage*)imageByScalingToSize:(CGSize)destinationSize image:(UIImage*)originalImage;
-(UIImage*)getResizedImage:(UIImage *)flagImage;
-(void)goToMyLocation;
-(void)goToCompany;

@end

@implementation MapViewController

@synthesize delegate;
@synthesize closecallback;
@synthesize selectcallback;
@synthesize latitude;
@synthesize longitude;
@synthesize IsEdit;
@synthesize IsEmpty;

-(id)init{
    self=[super initWithNibName:@"MapViewController" bundle:nil];
    return self;
}

-(void)refershLocation{
    [self LoadData];
    [self goToCompany];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    [self viewDidUnload];
}

-(void)viewDidUnload{
    locationList=nil;
    self.delegate=nil;
    self.closecallback=nil;
    self.selectcallback=nil;
    
    if (omapview) {
        omapview.delegate=nil;
        [omapview removeFromSuperview];
        omapview =nil;
    }
    [self setBtnSelect:nil];
    [super viewDidUnload];
}

-(void)Cancel{
    if (omapview) {
        omapview.delegate=nil;
        [omapview removeFromSuperview];
        omapview =nil;
    }
}

-(IBAction)SelectClick:(id)sender{
    clsLocationData * newLocation=[locationList objectAtIndex:0];
    self.latitude=newLocation.coordinate.latitude;
    self.longitude=newLocation.coordinate.longitude;
    if (selectcallback) {
        selectcallback();
    }
    
    [self performSelector:@selector(CloseClick:) withObject:nil afterDelay:0.3];
}

-(IBAction)CloseClick:(id)sender{   
    [self Cancel];
    [self.view removeFromSuperview];
    
    if (delegate) {
        [delegate CloseMapView];
        delegate=nil;
    }
    if (closecallback) {
        closecallback();
    }
    if (locationList) {
        [locationList removeAllObjects];
        locationList=nil;
    }
}

/*
- (IBAction)BtnGoToCLocation:(id)sender {
	[self goToMyLocation];
}

- (IBAction)BtnGoToCompany:(id)sender {
	[self goToCompany];
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (_IOS8) {
        //是否具有定位权限
        BOOL enable=[CLLocationManager locationServicesEnabled];
        int status=[CLLocationManager authorizationStatus];
        if(!enable || status<3){
            //请求权限
            olocationmanager = [[CLLocationManager alloc] init];
            [olocationmanager requestAlwaysAuthorization];
        }
    }

    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        CGRect screenbounds=[[UIScreen mainScreen] bounds];
        [self.view setFrame:CGRectMake(0, 22, screenbounds.size.width, screenbounds.size.height-22)];
        
        if (screenbounds.size.height==568) {
            for (UIView *subview in self.view.subviews) {
                [subview setFrame:CGRectMake(subview.frame.origin.x, subview.frame.origin.y+50, subview.frame.size.width, subview.frame.size.height)];
            }
        }
    }
    
	//isAddLocation=NO;
	isLoadingData=NO;
	isSetingData=NO;
	omapview.delegate=self;
    [self.btnSelect setTitle:[cLanguage getString:@"SET152"]forState:UIControlStateNormal];
    [self.btnClose setTitle:[cLanguage getString:@"SET157"]forState:UIControlStateNormal];
	[self LoadData];
    [self goToCompany];
    if (IsEdit==NO) {
        [self.btnSelect setHidden:YES];
    }
    omapview.showsUserLocation=YES;
    
    if (IsEdit==YES) {
        UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGesture:)];
        [omapview addGestureRecognizer:longPressGesture];
    }
}

-(void)handleLongPressGesture:(UIGestureRecognizer*)sender {
    CGPoint point = [sender locationInView:omapview];
    CLLocationCoordinate2D locCoord = [omapview convertPoint:point toCoordinateFromView:omapview];
    
    clsLocationData * newLocation=[locationList objectAtIndex:0];
    [newLocation setCoordinate:locCoord];
    
    IsEmpty=NO;
}

-(void)CreateCompanyData{
    CLLocationCoordinate2D newCoord={self.latitude,self.longitude};
    clsLocationData * newLocation= [[clsLocationData alloc] init];
    newLocation.coordinate=newCoord;
    if (IsEdit==YES) {
        newLocation.name=@"樓盤所在位置";
    }
    /*
    newLocation.image=nil;
    if (![oclsCompany.Logo isEqualToString:@""]) {
        NSString *path = [NSString stringWithFormat:@"%@/%@", [clsFileFun getCompanyDir:oclsCompany.CompanyType :oclsCompany.CompanyID], oclsCompany.Logo];
        BOOL success = [[NSFileManager defaultManager] fileExistsAtPath:path];
        if(success) {
            newLocation.image = [UIImage imageWithContentsOfFile:path];
        }
    }
    if (newLocation.image==nil) {
        newLocation.image = [UIImage imageNamed:@"no_product_item_photo.png"];
    }
    newLocation.image=[self imageByScalingToSize:CGSizeMake(32, 32) image:newLocation.image];
    */
    
    [locationList addObject:newLocation];
    newLocation=nil;
}

-(void)LoadData{
	isLoadingData=YES;
    locationList = [[NSMutableArray alloc] initWithCapacity:0];
    [self CreateCompanyData];
    //[BtnShowCompanyLoc setTitle:@"當前公司" forState:UIControlStateNormal];
	isLoadingData=NO;
    
	isSetingData=YES;
	//if([omapview getZoomLevel]>=Zoom_Min_Level){
    for (id <MKAnnotation> annotation in [omapview annotations]) {
        if (![annotation isKindOfClass:[MKUserLocation class]])
            [omapview removeAnnotation:annotation];
    }
    
    [omapview addAnnotations:locationList];
    //isAddLocation=YES;
	//}
	isSetingData=NO;
}

-(UIImage*)imageByScalingToSize:(CGSize)destinationSize image:(UIImage*)originalImage
{
	@try {
		UIGraphicsBeginImageContext(destinationSize);
		[originalImage drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
		UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
		UIGraphicsEndImageContext();
		return newImage;
	}
	@catch (NSException * e) {
		return originalImage;
	}
}

#define annotation_Padding 10.0f
#define callout_Height 40.0f
-(UIImage*)getResizedImage:(UIImage *)flagImage
{
	CGRect resizeRect;
	resizeRect.size = flagImage.size;
	CGSize maxSize = CGRectInset(omapview.bounds,annotation_Padding,annotation_Padding).size;
	maxSize.height -= callout_Height;
	if (resizeRect.size.width > maxSize.width)
		resizeRect.size = CGSizeMake(maxSize.width, resizeRect.size.height / resizeRect.size.width * maxSize.width);
	if (resizeRect.size.height > maxSize.height)
		resizeRect.size = CGSizeMake(resizeRect.size.width / resizeRect.size.height * maxSize.height, maxSize.height);
	
	resizeRect.origin = (CGPoint){0.0f, 0.0f};
	UIGraphicsBeginImageContext(resizeRect.size);
	[flagImage drawInRect:resizeRect];
	UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	
	return resizedImage;
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
	if ([annotation isKindOfClass:[MKUserLocation class]]) {
        MKUserLocation *userlocation=annotation;
		userlocation.title=[cLanguage getString:@"SET158"];
		return nil;
	}
    
	if ([annotation isKindOfClass:[clsLocationData class]]) {
		static NSString* LocationIdentifier = @"LocationIdentifier";
        MKAnnotationView* locationview =
        (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:LocationIdentifier];
        if (!locationview)
        {
            locationview = [[MKPinAnnotationView alloc] initWithAnnotation:annotation
                                                        reuseIdentifier:LocationIdentifier];
            /*
            locationview = [[MKAnnotationView alloc] initWithAnnotation:annotation
                                                        reuseIdentifier:LocationIdentifier];
            locationview.canShowCallout = YES;
            locationview.opaque = NO;
            */
			/*
			UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
			UIImage *icon=[UIImage imageNamed:@"g_calloutinfo.png"];
			[button setImage:icon forState:UIControlStateNormal];
			[button setImage:icon forState:UIControlStateHighlighted];
			locationview.rightCalloutAccessoryView = button;
			button=nil;
			icon=nil;
            */
        }
        else
        {
            locationview.annotation = annotation;
        }
        if (IsEdit==YES) {
            locationview.draggable = YES;
        }
		
        /*
		clsLocationData *locationdata=annotation;
		UIImage *flagImage;
        flagImage = [UIImage imageNamed:@"g_other.png"];
        flagImage=[self imageByScalingToSize:CGSizeMake(38, 40) image:flagImage];
		locationview.image =[self getResizedImage:flagImage];
		flagImage=nil;
		
        if (locationdata.image!=nil) {
            UIImageView *iconView = [[UIImageView alloc] initWithImage:locationdata.image];
            locationview.leftCalloutAccessoryView = iconView;
        }
		locationdata=nil;
        */
		
        return locationview;
	}
    
	return nil;
}

-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control{
    if ([view.annotation isKindOfClass:[clsLocationData class]]) {
        /*
         clsLocationData *locationdata=view.annotation;
         
         UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"你选择的是:" message:locationdata.title delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
         [alert show];
         
         locationdata=nil;
         */
	}
}

/*
- (void)buttonclick:(id)sender{
    [self CloseClick:nil];
}
*/

- (void)mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error{
	//UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"錯誤" message:@"載入地圖數據失敗!" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
	//[alert show];
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState {
	
	if (newState == MKAnnotationViewDragStateEnding) {
        IsEmpty=NO;
    }
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    //完成显示当前位置
    if (userLocation.coordinate.latitude==0 || userLocation.coordinate.longitude==0) {
        return;
    }
    if (IsEmpty) {
        [self goToMyLocation];
        
        clsLocationData * newLocation=[locationList objectAtIndex:0];
        [newLocation setCoordinate:userLocation.coordinate];
        
        IsEmpty=NO;
    }
}

//Locate Fun
-(void)goToMyLocation{
	CLLocationCoordinate2D centerCoord = omapview.userLocation.coordinate;
    [omapview setCenterCoordinate:centerCoord zoomLevel:Default_Zoom_Level animated:NO];
}

-(void)goToCompany{
    CLLocationCoordinate2D centerCoord= {latitude,longitude};
    [omapview setCenterCoordinate:centerCoord zoomLevel:Default_Zoom_Level animated:NO];
}

//Zoom Level
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
	if (isLoadingData==YES || isSetingData==YES) {
		return;
	}
	
    /*
     if([omapview getZoomLevel]<Zoom_Min_Level){
     if (isAddLocation==YES) {
     
     [omapview removeAnnotations:locationList];
     isAddLocation=NO;
     
     }
     }else {
     if (isAddLocation==NO) {
     [omapview addAnnotations:locationList];
     isAddLocation=YES;
     }
     }
     */
}

@end
